package org.example.day04;

import java.util.ArrayList;
import java.util.List;

/**
 * 第二章节:2.2.7.2产生线程安全问题
 */
public class MyOneList {
    //只能存放一个元素的list
    private List list = new ArrayList<>();
    synchronized public void add(String data){
        list.add(data);
    }
    synchronized public int getSize(){
        return list.size();
    }

    public static void main(String[] args) throws InterruptedException {
        MyOneList ml = new MyOneList();
        Thread10A ta = new Thread10A(ml);
        ta.setName("A");
        ta.start();
        Thread10B tb = new Thread10B(ml);
        tb.setName("B");
        tb.start();
        Thread.sleep(6000);
        System.out.println("listSize = " + ml.getSize());
    }
}

//class MyService {
//    public MyOneList addServiceMethod(MyOneList ml,String data){
//        try {
//            //只能存放一个元素的list
//            if(ml.getSize() < 1){
//                //睡眠保证两个线程都能通过if判断进来,产生线程安全问题
//                Thread.sleep(2000);
//                ml.add(data);
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        return ml;
//    }
//}

class MyService {
    public MyOneList addServiceMethod(MyOneList ml,String data){
        try {
            synchronized (ml){
                //不加synchronized会出现线程安全问题
                if(ml.getSize() < 1){
                    Thread.sleep(2000);
                    ml.add(data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ml;
    }
}

class Thread10A extends Thread{
    private MyOneList ml;
    public Thread10A(MyOneList ml) {
        this.ml = ml;
    }

    @Override
    public void run() {
        MyService ms = new MyService();
        ms.addServiceMethod(ml,"A");
    }
}
class Thread10B extends Thread{
    private MyOneList ml;

    public Thread10B(MyOneList ml) {
        this.ml = ml;
    }

    @Override
    public void run() {
        MyService ms = new MyService();
        ms.addServiceMethod(ml,"B");
    }
}

//listSize = 2